package org.ccheng.xztx.util;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.map.MapUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpUtil;
import org.ccheng.common.BeanUtil;

import java.util.*;

public class Api {

    public static String get(String api) {
        Map<String, Object> params = MapUtil.newHashMap();
        params.put("time", DateUtil.now());
        return get(api, params);
    }

    public synchronized static String get(String api, Map<String, Object> data) {
        String url = ApiConstants.SERVER_URL + api;

        if (data == null)
            data = new HashMap<>();

        data.put("sid", ApiConstants.USER_SID);

        try {
            Thread.sleep(500);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        HttpRequest httpRequest = HttpUtil.createGet(url, true);
        String response = httpRequest.form(data).execute().body();
        response = response.replaceAll("&nbsp;", "");
        response = response.replaceAll("&middot;", "·");
        response = response.replaceAll("&amp;", "&");
        return response;
    }

    public static <T> T get(String api, Map<String, Object> data, Class<T> type) {
        String response = get(api, data);
        return BeanUtil.toBean(response, type);
    }

    public static <T> T get(String api, Class<T> type) {
        return get(api, null, type);
    }

    public synchronized static void out(String... str) {
        StringBuilder sb = new StringBuilder();
        Arrays.stream(str).forEach(s -> sb.append(s));

        new Thread(() -> {
            System.out.println(sb);
        }).start();
    }

}
